package com.beatingapp;

import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.engine.options.EngineOptions;
import org.andengine.entity.scene.Scene;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.texture.ITexture;
import org.andengine.opengl.texture.bitmap.BitmapTexture;
import org.andengine.util.adt.io.in.IInputStreamOpener;
import org.andengine.util.debug.Debug;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegionFactory;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;

import com.beatingapp.clases.SoundMeter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;

public class ApagarCigarrilloActivity extends SimpleBaseGameActivity{

	private static int CAMERA_WIDTH= 800;
	private static int CAMERA_HEIGHT = 480;
	private ITextureRegion mBackgroundTextureRegion, mCigaretteOnFireTextureRegion, mCigaretteTextureRegion, mFuegoTextureRegion;
	private Sprite mCigaretteOnFire, mFuego;
	  /** running state **/
    private boolean mRunning = false;
    
    /** config state **/
    private int mThreshold = 25000;
    
    private PowerManager.WakeLock mWakeLock;

    private Handler mHandler = new Handler();
    private SoundMeter mSensor;
	private static final int POLL_INTERVAL = 300;
	
    
    private Runnable mSleepTask = new Runnable() {
            public void run() {
            	//Log.i("Noise", "runnable mSleepTask");
                    
            	start();
            }
    };
    
   
	public EngineOptions onCreateEngineOptions() {
		Toast.makeText( getApplicationContext(), "El cigarrillo esta encendido, sopla el microfono para apagarlo!", Toast.LENGTH_SHORT ).show( );
		
		  mSensor = new SoundMeter();
          PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	      mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "NoiseAlert");
		final Camera camera = new Camera (0,0, CAMERA_WIDTH, CAMERA_HEIGHT); 
		return new EngineOptions (true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera );
	}

	@Override
	protected void onCreateResources() {
		
		 mSensor = new SoundMeter();
		 
		 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
         mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "NoiseAlert");
		
		// TODO Auto-generated method stub
		//1. Set up bitmap textures
		
		try{
			ITexture backgroundTexture = new BitmapTexture (this.getTextureManager(), new IInputStreamOpener() {
				
				@Override
				public InputStream open() throws IOException {
					// TODO Auto-generated method stub
					return getAssets().open("gfx/background.jpg");
				}
			});
			ITexture FuegoTexture = new BitmapTexture (this.getTextureManager(), new IInputStreamOpener() {
				
				@Override
				public InputStream open() throws IOException {
					// TODO Auto-generated method stub
					return getAssets().open("gfx/fuego.png");
				}
			});
			ITexture cigaretteOnFireTexture = new BitmapTexture (this.getTextureManager(), new IInputStreamOpener() {
				
				@Override
				public InputStream open() throws IOException {
					// TODO Auto-generated method stub
					return getAssets().open("gfx/cigaretteOnFire.jpg");
				}
			});
			ITexture cigaretteTexture = new BitmapTexture (this.getTextureManager(), new IInputStreamOpener() {
				
				@Override
				public InputStream open() throws IOException {
					// TODO Auto-generated method stub
					return getAssets().open("gfx/cigarette.jpg");
				}
			});
			
		//2. - Load bitmap textures into VRAN
			backgroundTexture.load();
			cigaretteOnFireTexture.load();
			cigaretteTexture.load();
			FuegoTexture.load();
			
			// 3. Set up texture regions
			this.mBackgroundTextureRegion = TextureRegionFactory.extractFromTexture(backgroundTexture);
			this.mCigaretteOnFireTextureRegion = TextureRegionFactory.extractFromTexture(cigaretteOnFireTexture);
			this.mCigaretteTextureRegion = TextureRegionFactory.extractFromTexture(cigaretteTexture);
			this.mFuegoTextureRegion = TextureRegionFactory.extractFromTexture(FuegoTexture);
		} catch (IOException e){
			Debug.e(e);
		}
	}

	@Override
	protected Scene onCreateScene() {
		// TODO Auto-generated method stub
		// 1 - Create new scene
		final Scene scene = new Scene();
		Sprite backgroundSprite = new Sprite (0,0,this.mBackgroundTextureRegion,getVertexBufferObjectManager());
		scene.attachChild(backgroundSprite);
		
		// 2 - Add the cigarette
		
		mCigaretteOnFire = new Sprite(100,300, this.mCigaretteOnFireTextureRegion, getVertexBufferObjectManager());
		mFuego = new Sprite (60, 150, this.mFuegoTextureRegion, getVertexBufferObjectManager());
		
		scene.attachChild(mCigaretteOnFire); 	
		scene.attachChild(mFuego);
		
		return scene;
	}
	
	
	
	 public void onResume() {
         super.onResume();
         //Log.i("Noise", "==== onResume ==="); 
         if (!mRunning) {
             mRunning = true;
             start();
         }
 }

 @Override
 public void onStop() {
         super.onStop();
         Log.i("Noise", "==== Stop Noise Monitoring===");
         if (mWakeLock.isHeld()) {
                 mWakeLock.release();
         }
         mHandler.removeCallbacks(mSleepTask);
         mHandler.removeCallbacks(mPollTask);
         mSensor.stop();
         mRunning = false;
        
 }

 private void start() {
 	    //Log.i("Noise", "==== start ===");
 	
         mSensor.start();
         if (!mWakeLock.isHeld()) {
                 mWakeLock.acquire();
         }
         
         //Noise monitoring start
         // Runnable(mPollTask) will execute after POLL_INTERVAL
         mHandler.postDelayed(mPollTask, POLL_INTERVAL);
 }


 private Runnable mPollTask = new Runnable() {
     public void run() {
     	
             double amp = mSensor.getAmplitude();
             //Log.i("Noise", "runnable mPollTask");
          

             if ((amp > mThreshold)) {
            	 
            	 Toast.makeText( getApplicationContext(), "Cigarrillo Apagado =D", Toast.LENGTH_SHORT ).show( );
            	
                   //Log.i("Noise", "==== onCreate ===");
                   
             }
             
             // Runnable(mPollTask) will again execute after POLL_INTERVAL
             mHandler.postDelayed(mPollTask, POLL_INTERVAL);
          
     }
};
 
 

}
